package com.example.fontposition.dao.search.impl;

import cn.tedu.common.pojo.vo.PageData;
import cn.tedu.common.util.PageInfoToPageDataConverter;
import cn.tedu.zhaopin.protocol.position.vo.PositionSimpleVO;
import com.example.fontposition.dao.persest.mapper.PositionMapper;
import com.example.fontposition.dao.search.IPositionESRepository;
import com.example.fontposition.dao.search.PositionElasticsearchRepository;
import com.example.fontposition.pojo.po.PositionPO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class PositionESRepositoryImpl implements IPositionESRepository {

    @Autowired
    private PositionElasticsearchRepository positionElasticsearchRepository;


    @Override
    public void saveAll(List<PositionSimpleVO> List) {
        positionElasticsearchRepository.saveAll(List);
    }

    @Override
    public void deleteAll() {
        positionElasticsearchRepository.deleteAll();
    }

    @Override
    public PageData<PositionSimpleVO> search(String title, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(--pageNum, pageSize);
        SearchPage<PositionSimpleVO> searchPage = positionElasticsearchRepository.customSearch(title, pageable);

        SearchHits<PositionSimpleVO> searchHits = searchPage.getSearchHits();

        PageData<PositionSimpleVO> pageData = new PageData<>();
        pageData.setPageNum(pageNum + 1);
        pageData.setPageSize(pageSize);
        pageData.setMaxPage(searchPage.getTotalPages());
        pageData.setTotal(searchHits.getTotalHits());

        List<PositionSimpleVO> positionPOList = new ArrayList<>();
        for (SearchHit<PositionSimpleVO> searchHit : searchHits) {
            PositionSimpleVO PositionSimpleVO = searchHit.getContent();
            positionPOList.add(PositionSimpleVO);
        }
        pageData.setList(positionPOList);

        return pageData;
    }
    }

